package com.treasure.mall.zbqmallapi.websocket;

import com.treasure.mall.biz.bo.SystemInfoData;
import com.treasure.mall.biz.entity.live.LiveSessionPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.mapstruct.UserMapStruct;
import com.treasure.mall.biz.remote.live.TencentIMService;
import com.treasure.mall.biz.remote.live.TencentTools;
import com.treasure.mall.biz.remote.live.dto.JoinMessageDTO;
import com.treasure.mall.biz.service.core.live.LiveSessionService;
import com.treasure.mall.biz.service.core.user.UserService;
import com.treasure.mall.biz.vo.user.UserVO;
import com.treasure.mall.zbq.common.ienum.live.LiveEnums;
import org.apache.commons.lang3.StringUtils;

import javax.websocket.Session;
import java.util.List;
import java.util.Map;

/**
 *
 * <p> websocket 基类
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.zbqmallapi.websocket
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/9/18 10:43 上午
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * 
 */
public class WebSocketBase {

    /**
     * 与某个客户端的连接对话，需要通过它来给客户端发送消息
     */
    protected Session session;

    protected static LiveSessionService liveSessionService;
    protected static UserService userService;
    protected static TencentIMService imService;

    /**
     * 获取请求参数
     *
     * @param key
     * @return
     */
    protected String getRequestParameter(String key) {
        return getRequestParameter(key, "");
    }

    /**
     * 获取请求参数
     *
     * @param key
     * @param defaultValue
     * @return
     */
    protected String getRequestParameter(String key, String defaultValue) {
        try {
            if (session != null) {

                Map<String, List<String>> map = session.getRequestParameterMap();
                if (map != null && map.containsKey(key)) {
                    return map.get(key).get(0);
                }
            }
        } catch (Exception ignored) {

        }
        return defaultValue;

    }

    protected String getHeader(String key, String defaultValue) {
        try {
            if (session != null) {
                Map<String, String> header = (Map<String, String>) session.getUserProperties().get("headers");
                if (header != null && header.containsKey(key)) {
                    return header.get(key);
                }
            }
        } catch (Exception ignored) {

        }
        return defaultValue;
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    protected UserVO getUserInfo() {
        String token = getHeader("X-token", "");
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        UserPO userPO = userService.findByToken(token);
        if (userPO != null) {
            return UserMapStruct.INSTANCE.po2vo(userPO);
        }
        return null;
    }

    /**
     * 获取系统信息
     *
     * @return
     */
    protected SystemInfoData getSystemInfo() {
        SystemInfoData systemInfoData = new SystemInfoData();
        systemInfoData.setClient(getHeader("X-client", ""));
        systemInfoData.setSystemInfo(getHeader("X-systemInfo", ""));
        systemInfoData.setSystemVersion(getHeader("X-systemVersion", ""));
        systemInfoData.setVersion(getHeader("X-version", ""));
        systemInfoData.setScene(getHeader("X-scene", ""));
        return systemInfoData;
    }


    /**
     * 检查是否无效请求
     *
     * @param userId
     * @param sessionId
     * @return
     */
    protected boolean checkInvalid(Long userId, String sessionId) {
        if (userId == null || StringUtils.isEmpty(sessionId)) {
            return true;
        }
        LiveSessionPO sessionPO = liveSessionService.findById(sessionId);
        if (sessionPO == null) {
            return true;
        }
        if (!sessionPO.getPlayStatus().equals(LiveEnums.PlayStatus.PAYING)) {
            return true;
        }
        return false;
    }

    /**
     * 发送进入直播间接口
     *
     * @param userId    用户ID
     * @param sessionId 直播间ID
     */
    protected void sendJoinRoomMessage(Long userId, String sessionId) {
        try {
            UserPO user = userService.findById(userId);
            if (user != null) {
                // 发送加入直播间消息
                imService.join(JoinMessageDTO.builder()
                        .name(user.getNickName())
                        .liveSessionId(sessionId)
                        .level(TencentTools.getMessageUserLevel(user.getValidPayOrderSum()))
                        .build()
                );
            }
        } catch (Exception ignored) {

        }
    }
}
